#!/usr/bin/python

#Ganna Raboshchuk {ganna.raboshchuk@upc.edu}
#22.10.2013
#UPC, Barcelona

#Get the resultant scores with ACC metric.
#Only alarms are taken into account.
#--------------------------------------------------------------------------

import sys

START_TIME = 0
END_TIME = 1
CLASS = 2

class_of_interest = 'al'

resultsFolder = sys.argv[1]
P_array = sys.argv[2].split(';')
labFile = sys.argv[3]

#resultsFolder = '/home/anna/Hospital/Segmentation/Alarms_detection/Code_bash/recognition/Ch24_C24_ff_d_S3_G3_out_30-10_44100_all18/S3'
#P_array = [-10]
#labFile = '/home/anna/Hospital/Segmentation/Alarms_detection/Code_bash/data/lab/1_SCDB_31.mlf'

#Read the reference labelling for a specified file 
def getReference(filename, labFile): 
    reference = []
    labelling = open(labFile, 'r')
    readLabels = False
    for line in labelling:
        if (line == '"*/' + filename + '.lab"\n' ):
            readLabels = True
        if (line == '.\n') and readLabels:
            break
        if line[0].isdigit() and readLabels:            
            labels = line.split()
            timestamps = range(int(round((float(labels[END_TIME])-float(labels[START_TIME]))*100)))
            for i in timestamps:
                reference.append(labels[CLASS])
    return reference        

#--------------------------------------------------------------------------
#MAIN code
tokens = resultsFolder.split('/')
session = tokens[-1]
tokens = tokens[:-1]
outputFolder = '/'.join(map(str,tokens))

resultantLog = outputFolder + '/FINAL_RESULTS_frames.log'

overallResults = open(resultantLog, 'a')
overallResults.write(session + '\n')
  
for p in P_array:        
    #resultFile = resultsFolder + '/out_merged_' + str(p) + '.mmf'
    resultFile = resultsFolder + '/out_smooth_' + str(p) + '.mmf'
    results = open(resultFile, 'r')
    
    hypothesis = []
    reference = []
    for line2 in results:
        line = line2
        if not line[0].isdigit():
            if (line != '#!MLF!#\n'):
                if (line != '.\n'): #filename string
                    tokens = line.split('/')
                    filename = tokens[len(tokens)-1].split('.')[0]
                    reference = reference + getReference(filename, labFile)                                        
        else:
            labels = line.split()
            hypothesis.append(labels[CLASS])

    total_number = len(hypothesis)
    l2 = len(reference) 
    #print total_number + ' ' + l2
    reference = reference[:len(hypothesis)]
    #Checking only frames with alarms          
    #matched = [i for i, j in zip(reference, hypothesis) if i == j]
    #acc = len(matched)
    missed = 0
    matched = 0
    false_alarm = 0
    total_frames = 0 #total number of referenced alarms frames
    for i in range(len(hypothesis)):
        if reference[i] == class_of_interest:
            total_frames += 1
            missed += (reference[i] != hypothesis[i])
            matched += (reference[i] == hypothesis[i])
        if hypothesis[i] == class_of_interest and reference[i] != class_of_interest:
            false_alarm += 1
                
    errors = false_alarm + missed

    #Logging information
    overallResults.write(str(p) + '\t FA: ' + str(false_alarm) + ', MS: ' + str(missed) + ', MA: ' + str(matched) + '\n')
    overallResults.write('\t Total vo: ' +  str(total_frames) + ', Total frames: ' + str(total_number) + '\n')
    
    #found = [x for x in hypothesis if x == class_of_interest]
    if total_number == 0:
        overallResults.write('No reference samples found.\n')
    else:
        acc = (1 - errors/float(total_number))*100
        overallResults.write(str(p) + '\t' + str(acc) + '\n')
        print acc
                    
                    
                

                    
            
    
